package com.jo.util;

import com.google.common.collect.Lists;
import com.jo.advisor.Advice;
import com.jo.advisor.AdvisedSupport;
import com.jo.advisor.Advisor;
import com.jo.register.DefaultAdviseAdapterRegister;
import com.jo.interceptor.AdviseAdapter;
import com.jo.interceptor.MethodInterceptor;

import java.util.List;

/**
 * aop工具类
 * @author Jo
 * @date 2018/1/26
 */
public class AopUtil {

    /**
     * 默认advice适配器工厂实例
     */
    private static DefaultAdviseAdapterRegister adapterRegister = new DefaultAdviseAdapterRegister();

    /**
     * 根据AdvisedSupport获取方法拦截器链
     * @param config
     * @return
     */
    public static List<MethodInterceptor> getMethodInterceptors(AdvisedSupport config) {
        List<MethodInterceptor> interceptors = Lists.newArrayList();
        for (Advisor advisor : config.getAdvisors()) {
            Advice advice = advisor.getAdvice();
            if (advice instanceof MethodInterceptor){
                MethodInterceptor methodInterceptor = (MethodInterceptor) advice;
                interceptors.add(methodInterceptor);
            }

            for (AdviseAdapter adviseAdapter : adapterRegister.getAdviseAdapters()) {
                if (adviseAdapter.support(advice)){
                    interceptors.add(adviseAdapter.convert(advice));
                }
            }
        }

        return interceptors;
    }
}
